import { getApkUpgrade } from '@/api/system/app'
import config from '@/config'

const deviceInfo = {
  state: {
    systemInfo: '', // 系统信息
    upgradeInfo: null // 升级信息
  },

  mutations: {
    SET_SYSTEM_INFO: (state, systemInfo) => {
      state.systemInfo = `${systemInfo.appWgtVersion},${systemInfo.deviceBrand} ${systemInfo.deviceModel},${systemInfo.osName} ${systemInfo.osVersion},${systemInfo.romName} ${systemInfo.romVersion}`
    },
    SET_UPGRADE_INFO: (state, upgradeInfo) => {
      state.upgradeInfo = upgradeInfo
    }
  },

  actions: {
    // 获取app升级信息
    GetUpgradeInfo({ commit, state }, allowSkip = false) {
      return new Promise((resolve, reject) => {
        plus.runtime.getProperty(plus.runtime.appid, async (info) => {
          getApkUpgrade().then((res) => {
            if (res.code == 200 && res.data && res.data.appUrl) {
              if (info.versionCode >= res.data.version) {
                reject('已是最新版')
                return
              }

              if (allowSkip && res.data.strategy != 1) {
                reject('跳过更新')
                return
              }

              const PACKAGE_INFO_KEY = '__package_info__'
              const result = {
                version: res.data.versionDescription,
                description: res.data.upgradeDescription,
                url: config.staticUrl + res.data.appUrl,
                updateForce: res.data.strategy == 1
              }
              commit('SET_UPGRADE_INFO', result)
              uni.setStorageSync(PACKAGE_INFO_KEY, result)
              uni.showToast({
                title: res.code
              })
              setTimeout(() => {
                uni.reLaunch({
                  url: `/pages/upgrade/upgrade?key=${PACKAGE_INFO_KEY}`,
                  success: () => {
                    resolve('有新版本')
                  },
                  fail: (err) => {
                    console.error('更新弹框跳转失败', err)
                    uni.removeStorageSync(PACKAGE_INFO_KEY)
                    resolve('更新弹框跳转失败')
                  }
                })
              }, 500)
            } else {
              reject('已是最新版')
            }
          })
        })
      })
    }
  }
}

export default deviceInfo
